package model

import (
	"time"

	"github.com/jinzhu/gorm"
)

type Course struct {
	*Model
	Name         string `json:"name"`
	Description  string `json:"description"`
	ChainName    string `json:"chain_name"`
	ChainAccount string `json:"chain_account"`
	Username     string `json:"username"`
	Start        int    `json:"start"`
	End          int    `json:"end"`
}

func (c *Course) TableName() string {
	return "course"
}

func (c *Course) Create(db *gorm.DB) error {
	return db.Create(c).Error
}

func (c *Course) GetMy(db *gorm.DB) ([]*Course, error) {
	var courses []*Course
	err := db.Where("username = ? AND is_del = ?", c.Username, 0).Find(&courses).Error
	return courses, err
}

func (c *Course) GetAll(db *gorm.DB) ([]*Course, error) {
	var courses []*Course
	err := db.Where("is_del = ?", 0).Find(&courses).Error
	return courses, err
}

func (c *Course) GetCurrent(db *gorm.DB) ([]*Course, error) {
	var courses []*Course
	current := time.Now().Unix()
	err := db.Where("start < ? AND end > ? AND is_del = ?", current, current, 0).Find(&courses).Error
	return courses, err
}

func (c *Course) Delete(db *gorm.DB, id int) error {
	return db.Where("id = ?", id).Delete(c).Error
}
